package cn.tedu.interceptor;

import cn.tedu.util.ThumbnailGenerator;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 缩略图拦截器
 *
 * @author Kiven
 */
@Configuration
public class ImageInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 提取图片URL
        String imageUrl = request.getRequestURI().replace("/thumbnail/", "");
        // 返回缩略图
        try {
            int thumbnailWidth = 100;
            int thumbnailHeight = 100;
            byte[] thumbnailData = generateThumbnail(imageUrl, thumbnailWidth, thumbnailHeight);

            // 设置响应内容类型为image/jpeg
            response.setContentType("image/jpeg");
            response.setContentLength(thumbnailData.length);
            response.getOutputStream().write(thumbnailData);
            // 不继续执行后续处理器
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            // 处理生成缩略图失败的情况，可以返回默认缩略图或错误提示// 继续执行后续处理器
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理之后但渲染视图之前调用
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在渲染视图之后调用
    }

    private byte[] generateThumbnail(String imageUrl, int thumbnailWidth, int thumbnailHeight) throws IOException {
        // 动态生成缩略图的代码，与之前示例中的 ThumbnailGenerator.generateThumbnail() 方法相同
        return ThumbnailGenerator.generateThumbnail(imageUrl, thumbnailWidth, thumbnailHeight);
    }
}
